package com.yx.service.impl;


import com.yx.data.Result;
import com.yx.entity.SysMenu;
import com.yx.entity.SysMenuDisplay;
import com.yx.mapper.SysMenuMapper;
import com.yx.page.Page;
import com.yx.service.SysMenuService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;


/**
 * @Description: 用户
 * @Auther: zcz
 * @create 2020/4/16 11:51
 */
@Service
@Slf4j
public class SysMenuServiceImpl implements SysMenuService {

    @Autowired
    SysMenuMapper sysMenuMapper;

    /**
     * 获取展示菜单
     * @return 菜单列表
     */
    @Override
    public Result getDisplayMenus() {
        List<SysMenuDisplay> menus = sysMenuMapper.getMenusByParent("0");
        for (SysMenuDisplay menu : menus) {
            List<SysMenuDisplay> subs = this.setMenuTree(menu.getMenuId());
            if (0 == subs.size()) {
                continue;
            }
            menu.setSubMenus(subs);
        }
        return Result.data(getDisplayMenus(menus));
    }

    /**
     * 删除没有权限的菜单
     * @param menus
     * @return
     */
    public List<SysMenuDisplay> getDisplayMenus(List<SysMenuDisplay> menus) {
        Iterator<SysMenuDisplay> it = menus.iterator();
        while(it.hasNext()){
            SysMenuDisplay menu = it.next();
            if(!isPermitted(menu.getPermissionId())){
                it.remove();
                continue;
            }
            getDisplayMenus(menu.getSubMenus());
        }
        return menus;
    }

    private boolean isPermitted(String permissionId) {
        if (!SecurityUtils.getSubject().isAuthenticated()) {
            return false;
        }
        return !StringUtils.isNotBlank(permissionId) || SecurityUtils.getSubject().isPermitted(permissionId);
    }


    /**
     * 获取菜单树
     * @return 菜单树
     */
    private List<SysMenuDisplay> setMenuTree(String parentId) {
        List<SysMenuDisplay> menus = sysMenuMapper.getMenusByParent(parentId);
        for (SysMenuDisplay menu : menus) {
            List<SysMenuDisplay> subs = this.setMenuTree(menu.getMenuId());
            if (0 == subs.size()) {
                continue;
            }
            menu.setSubMenus(subs);
        }
        return menus;
    }
}
